import { defineStore } from 'pinia'
import { ref } from 'vue'
import { customConsultTypeApi } from '@/api'

export const useCustomConsultTypeStore = defineStore('customConsultType', () => {
  const options = ref<any[]>([])

  const fetchOptions = async () => {
    if (options.value.length > 0) {
      return options.value
    } else {
      options.value = await getProcessedData()
      return options.value
    }
  }
  const getProcessedData = async () => {
    try {
      const {
        data: { list },
      } = await customConsultTypeApi.getCustomConsultTypeList({ is_all: true })

      const processedData = list.map((item: any) => ({
        label: item.name,
        value: String(item.id),
        key: item.id,
      }))
      processedData.unshift({
        label: '非会员分成',
        value: '0',
        key: 0,
      })
      return processedData
    } catch (error) {
      console.error('获取全部自定义诊金类型数据失败:', error)
    }
  }

  // 根据key获取label
  const getLabelByKey = async (key: number) => {
    if (options.value.length === 0) {
      await fetchOptions()
    }
    const item = options.value.find((item: any) => item.key === key)
    return item ? item.label : '未知'
  }

  return {
    options,
    fetchOptions,
    getLabelByKey,
  }
})
